import { getPostApi, addPostApi, updatePostApi } from "@/apis/post";
import { useEffect, useState } from "react";
import Editer from "@/components/editer";
import { Form, Input, message, Modal } from "antd";
import style from "./index.module.css";
import PostIcon from "@/assets/svg/postIcon.svg?react";

export default function PostButton({ id, refreshPostList }: any) {
  const [post, setPost] = useState({
    title: "",
    content: "",
  });

  function handleRefreshPostList() {
    refreshPostList();
  }
  // const [loading, setLoading] = useState(false);
  const [isShow, setIsShow] = useState(false);

  const addPost = async () => {
    const api = id ? updatePostApi : addPostApi;
    try {
      // setLoading(true);
      const res: any = await api(post);
      if (res.code === 0) {
        message.success(id ? "更新成功" : "发帖成功");
        handleRefreshPostList();
        setIsShow(false);
      } else {
        message.error(
          id ? res.message || "更新失败" : res.message || "发帖失败"
        );
      }
    } catch (error) {
      message.error("请求失败");
    } finally {
      // setLoading(false);
    }
  };

  async function getPost() {
    try {
      const res: any = await getPostApi(id);
      if (res.code === 0) {
        setPost(res.data);
      }
    } catch (error) {}
  }

  useEffect(() => {
    if (id) {
      getPost();
    }
  }, []);
  return (
    <>
      <div
        className={style.postButtonContainer}
        onClick={() => setIsShow(true)}
      >
        <div className={style.postButton}>
          <PostIcon className={style.postIcon} />
        </div>
      </div>
      <Modal
        zIndex={1024}
        open={isShow}
        onCancel={() => {
          setIsShow(false);
        }}
        cancelText="取消"
        okText="完成"
        onOk={addPost}
        destroyOnClose
        width={"80%"}
      >
        <Form>
          <h2 className={style["form-title"]}>{id ? "编辑帖子" : "发帖"}</h2>
          <Form.Item
            label="标题"
            name="title"
            rules={[
              { required: true, message: "请输入标题" },
              { max: 50, message: "标题不能超过50字" },
            ]}
          >
            <Input
              value={post.title}
              onChange={(content: any) => {
                setPost({ ...post, title: content.target.value });
              }}
              placeholder="请输入标题（最多50字）"
              allowClear
            />
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[
              { required: true, message: "请输入内容" },
              {
                validator: (_, value) =>
                  value?.replace(/<[^>]+>/g, "").trim().length >= 10
                    ? Promise.resolve()
                    : Promise.reject("内容至少10字"),
              },
            ]}
          >
            <Editer post={post} setPost={setPost} />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
}
